package com.youku.component.notification;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.youku.component.report.TestReport;
import com.youku.util.FileHelper;
import com.youku.util.HtmlMailHelper;
import com.youku.util.TimeHelper;

/**
 * 将报告以email的形式发送
 * 
 * @author loda
 *
 */
public class EMailNotification implements Notification {

	private static final Logger logger = LoggerFactory.getLogger(EMailNotification.class);

	@Override
	public void notice(TestReport testReport, List<Recipient> recipients) {
		String text = testReport.format();
		logger.info("通过email的形式发送报告");
		String dir = NotificationController.getLocation();
		String fileName = new StringBuilder().append("reporter_").append(TimeHelper.formatNow()).append(".html")
				.toString();

		List<String> list = extractMailList(recipients);
		HtmlMailHelper.send("测试结果报告", text, list);
		logger.debug("给用户{}通过邮件的方式发送了测试报告",list.toString());
		logger.debug("将报告文件存储文件为:{}", new StringBuilder().append(dir).append(File.separator).append(fileName));
		try (BufferedWriter writer = new BufferedWriter(new FileWriter(FileHelper.createFileWithDirs(dir, fileName)))) {
			writer.write(text);
			writer.flush();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

	}

	private List<String> extractMailList(List<Recipient> recipients) {
		if (recipients == null || recipients.size() == 0)
			return Collections.emptyList();

		List<String> list = new LinkedList<>();

		for (Recipient recipient : recipients) {
			list.add(recipient.getEmail());
		}

		return list;
	}
}
